import { Context, Next } from "koa";
import { access, sql } from "../logger";
import { callbackData } from "../utils/data.handler";
import validate from "../utils/validator";
import { Rules } from "async-validator";
import RoleService from '../service/role.service'

export const roleValidator = async (ctx: Context, next: Next) => {
    const rules: Rules = {
        name: {
            type: 'string',
            required: true,
            message: '名称不能为空'
        },
        code: {
            type: 'string',
            required: true,
            message: '编码不能为空'
        }
    }
    const { error } = await validate<any>(ctx, rules);
    if (error) {
        access.info('角色信息校验错误', { msg: error })
        console.error('角色信息校验错误', { msg: error })
        ctx.app.emit('error', callbackData('1', error), ctx);
        return false;
    }
    await next();
}

//查重
export const verifyRole = async (ctx: Context, next: Next) => {
    const { name, code } = ctx.request.body || {};
    try {
        let res = await RoleService.findInfo({ name, code,id:'' });
        if (res) {
            sql.error('角色已存在', { name })
            console.error('角色已存在', { name })
            ctx.app.emit('error', callbackData('2', '角色已存在'), ctx);
            return false;
        }
    } catch (err) {
        sql.error('查询角色发生错误', err)
        console.error('查询角色发生错误', err)
        ctx.app.emit('error', callbackData('2', '角色信息错误'), ctx);
        return false;
    }
    await next();
}
